using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;

namespace DNAide.Web.UI
{
	public static partial class ControlAide
	{

		/// <summary>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="controls"></param>
		/// <param name="controlId"></param>
		/// <returns></returns>
		public static T FindControl<T>(ControlCollection controls, string controlId) where T : Control
		{
			if (controls == null)
			{
				throw new ArgumentException("controls null");
			}

			if (string.IsNullOrEmpty(controlId))
			{
				throw new ArgumentException("controlId is null or empty");
			}

			if (controls.Count < 1)
			{
				return null;
			}

			Control retval;
			foreach (Control control in controls)
			{
				if (control.ID == controlId)
				{
					return control as T;
				}
			}

			foreach (Control control in controls)
			{
				retval = FindControl<T>(control, controlId);
				if (retval != null)
				{
					return retval as T;
				}
			}
			return null;
		}


		/// <summary>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="control"></param>
		/// <param name="controlId"></param>
		/// <returns></returns>
		public static T FindControl<T>(Control control, string controlId) where T : Control
		{
			if (control == null)
			{
				throw new ArgumentException("control null");
			}

			if (control.Controls == null)
			{
				return null;
			}

			if (control.Controls.Count < 1)
			{
				return null;
			}

			Control retval;
			retval = control.FindControl(controlId);
			if (retval != null)
			{
				return retval as T;
			}

			foreach (Control childControl in control.Controls)
			{
				retval = FindControl<T>(childControl, controlId);
				if (retval != null)
				{
					return retval as T;
				}
			}

			return null;
		}
	}
}
